<template>
  <div class="oe-school-manage">
    <top-tip :title="title" :showBack="false"></top-tip>
    <div class="oe-school-contain">
      <p class="oe-manage-text">学校logo管理</p>
      <div class="oe-logo-upload">
        <div class="oe-img-box">
          <img
            width="566"
            height="102"
            :src="logoUrl || 'https://cdn-zjy.icve.com.cn/common/images/noCover.jpg'"
            alt="学校logo"
          />
        </div>
      </div>
      <div class="option-box">
        <div class="options">
          <button class="oe-upload-btn" @click.stop="showUploaderModal" v-if="operationList.includes('编辑')">
            上传
          </button>
          <div class="oe-text-boxs">
            <div class="oe-text-box">
              <a-checkbox
                :checked="stuIsShowSort"
                @change="stuIsShowSort = !stuIsShowSort"
                :disabled="!operationList.includes('编辑')"
                >学生端展示考试分类</a-checkbox
              >
            </div>
            <div class="oe-text-box">
              <a-checkbox
                :checked="stuIsShowBatch"
                @change="stuIsShowBatch = !stuIsShowBatch"
                :disabled="!operationList.includes('编辑')"
                >学生端展示考试批次</a-checkbox
              >
            </div>
            <div class="oe-text-box">
              <a-checkbox
                :checked="stuIsShowDoExam"
                @change="stuIsShowDoExam = !stuIsShowDoExam"
                :disabled="!operationList.includes('编辑')"
                >学生端展示即将开始的考试</a-checkbox
              >
            </div>
            <div class="oe-text-box">
              <a-checkbox
                :checked="stuIsIsOnlyDo"
                @change="stuIsIsOnlyDo = !stuIsIsOnlyDo"
                :disabled="!operationList.includes('编辑')"
                >考试时间相交内只允许学生作答一门考试</a-checkbox
              >
            </div>
          </div>
          <div class="oe-logo-save">
            <a-button key="submit" @click.stop="postLogo('')">保存</a-button>
          </div>
        </div>
      </div>

      <a-modal title="头像预览" v-model="modalVisibility" okText="保存" width="800px" wrapClassName="set-head-img">
        <template slot="footer">
          <a-button key="submit" type="primary" @click.stop="saveLogo">保存</a-button>
        </template>
        <div class="oe-cropper-logo">
          <div class="set-cropper-img">
            <vue-cropper
              ref="cropper"
              :aspect-ratio="5 / 1"
              :src="logoUrl || 'https://cdn-zjy.icve.com.cn/common/images/noCover.jpg'"
              style="height: 102px"
              centerBox
            />
          </div>
          <div class="set-cropper-btn">
            <a-button class style="position: relative; overflow: hidden" @change="setLogo">
              上传
              <input id="img-upload" ref="input" type="file" name="image" accept="image/*" />
            </a-button>
            <a-button class style="margin-left: 10px" @click="rotate(45)">
              <a-icon type="redo" />
            </a-button>
            <a-button class style="margin-left: 10px" @click="rotate(-45)">
              <a-icon type="undo" />
            </a-button>
          </div>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script>
import topTip from '@/components/top-tip/index.vue';
import VueCropper from 'vue-cropperjs';
import GetOperationList from '@/lib/mixin/methods.js';
import 'cropperjs/dist/cropper.css';
export default {
  mixins: [GetOperationList],
  components: {
    topTip,
    VueCropper,
  },
  data() {
    return {
      cropImgUrl: '',
      src: '',
      stuIsShowSort: false,
      stuIsShowDoExam: false,
      stuIsIsOnlyDo: false,
      stuIsShowBatch: false,
      logoUrl: '',
      operationList: [],
      IsOpList: [],
      modalVisibility: false,
      title: [{ text: '学校管理' }],
    };
  },
  mounted() {},
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.getOpeartion();
    });
  },
  methods: {
    // 判断是否是只读
    getIsWrite(type) {
      let index = this.IsOpList.findIndex((el) => {
        return el.Name === type;
      });
      if (index > -1) {
        if (this.IsOpList[index].IsRead && !this.IsOpList[index].IsWrite) {
          this.$message.info('您没有该操作权限！');
          return false;
        } else {
          return true;
        }
      }
    },
    // 获取页面操作
    getOpeartion() {
      this.loading = true;
      this.GetOperationList().then((rst) => {
        this.loading = false;
        this.operationList = [];
        this.IsOpList = [];
        if (rst.code === 1) {
          if (rst.list.length) {
            rst.list.forEach((item) => {
              this.operationList.push(item.Name);
              this.IsOpList = rst.list;
            });
          }
          this.getLogo();
        } else {
          this.$message.error(rst.msg);
        }
      });
    },
    showUploaderModal() {
      this.modalVisibility = true;
    },
    rotate(deg) {
      this.$refs.cropper.rotate(deg);
    },
    handleOk() {
      this.modalVisibility = false;
    },
    setLogo(e) {
      if (!this.getIsWrite('编辑')) {
        return;
      }
      const file = e.target.files[0];
      const fileSize = (file.size / 1024 / 1024).toFixed(0);
      if (fileSize > 5) {
        this.$message.error('请上传小于5M的图片');
        e.target.value = '';
        return;
      }
      if (file.type.indexOf('image/') === -1) {
        alert('Please select an image file');
        return;
      }
      if (typeof FileReader === 'function') {
        const reader = new FileReader();
        reader.onload = (event) => {
          this.imgSrc = event.target.result;
          this.$refs.cropper.replace(event.target.result);
        };
        reader.readAsDataURL(file);
      } else {
        alert('Sorry, FileReader API not supported');
      }
    },
    saveLogo() {
      if (!this.getIsWrite('编辑')) {
        return;
      }
      let completeUrl = (this.cropImg = this.$refs.cropper.getCroppedCanvas().toDataURL());
      let urlArr = completeUrl.split(',');
      let base64 = urlArr[1];

      let imgType = urlArr[0].replace('data:image/', '').replace(';base64', '');
      let file_system_url = localStorage.getItem('file_system_url');
      let postUrl = `${file_system_url}&extension=${imgType}&encode=base64`;
      this.$http.post(postUrl, base64).then((data) => {
        if (data) {
          this.cropImgUrl = data.url;
          localStorage.setItem('cropImgUrl', this.cropImgUrl);
          this.postLogo(data.url);
        }
      });
    },
    postLogo(url) {
      if (!this.getIsWrite('编辑')) {
        return;
      }
      if (!url) {
        url = this.url;
      }
      let stuIsShowSort = this.stuIsShowSort ? 1 : 0;
      let stuIsShowDoExam = this.stuIsShowDoExam ? 1 : 0;
      let stuIsShowBatch = this.stuIsShowBatch ? 1 : 0;
      let stuIsIsOnlyDo = this.stuIsIsOnlyDo ? 1 : 0;
      this.$http
        .get('/api/SchoolManager/school/save', {
          params: {
            url: url,
            stuIsShowSort: stuIsShowSort,
            stuIsShowDoExam: stuIsShowDoExam,
            stuIsShowBatch: stuIsShowBatch,
            stuIsIsOnlyDo: stuIsIsOnlyDo,
          },
        })
        .then((data) => {
          if (data.code === 1) {
            this.$message.success(data.msg);
            this.modalVisibility = false;
            this.getLogo();
          } else {
            this.$message.error(data.msg);
          }
        });
    },
    getLogo() {
      this.$http.get('/api/SchoolManager/school/getSchoolInfo').then((data) => {
        if (data.code === 1) {
          if (data.logoUrl) {
            localStorage.setItem('cropImgUrl', data.logoUrl);
            this.logoUrl = data.logoUrl;
          }
          this.url = data.url;
          this.stuIsShowSort = data.stuIsShowSort ? true : false;
          this.stuIsShowDoExam = data.stuIsShowDoExam ? true : false;
          this.stuIsShowBatch = data.stuIsShowBatch ? true : false;
          (this.stuIsIsOnlyDo = data.stuIsIsOnlyDo ? true : false), localStorage.setItem('logoUrl', this.logoUrl);
          this.$bus.$emit('getSchoolLogo', this.logoUrl);
        } else {
          this.$message.error(data.msg);
        }
      });
    },
  },
};
</script>
